﻿using System.Threading;

namespace Chimp.Core
{
    public class JobSceneUpdate : ChimpJob
    {
        public int Count;
        public int Start;

        public JobSceneUpdate(ChimpScene s, int start, int count)
        {
            S = s;
            Start = start;
            Count = count;
            PerformUpdate = true;
            UpdateDone = false;
        }

        private ChimpScene S { get; set; }

        public bool PerformUpdate { get; set; }
        public bool UpdateDone { get; set; }

        public override void PerformJob()
        {
            while (true)
            {
                Lock();
                if (PerformUpdate)
                {
                    PerformUpdate = false;
                    int i = 0;
                    if (Count > S.ObjectList.Count)
                    {
                        Count = S.ObjectList.Count;
                    }


                    S.ObjectLock.WaitOne();
                    foreach (ChimpBase obj in S.ObjectList.ToArray())
                    {
                        if (i >= Start)
                        {
                            if (i > Count)
                            {
                                break;
                            }

                            UpdateNodes(obj);
                        }
                        i++;
                    }
                    S.ObjectLock.ReleaseMutex();
                    UpdateDone = true;
                }
                Release();
                Thread.Sleep(8);
            }
        }

        private void UpdateNodes(ChimpBase obj)
        {
            S.UpdateObject(obj);
            foreach (ChimpBase n in obj.Nodes)
            {
                UpdateNodes(n);
            }
        }
    }
}